package com.spice.service.entity.job;

import com.spice.common.util.ShellUtil;
import com.spice.service.entity.pojo.BackupInfo;
import com.spice.service.service.BackupInfoService;
import lombok.Getter;

import java.io.File;
import java.util.Date;

/**
 * 备份任务
 * 用于后台备份数据
 */
@Getter
public class BackupJob extends Job {

    public static final String BACKUP_SHELL_PATH =
            new File("resources/shell/backup.sh").getAbsolutePath();

    public static final String DATABASE_NAME = "spice_info_platform";

    public static final File backupFolder = new File("resources/backup/");

    private String tableName;

    private String backupFilePath;

    private String details;

    BackupInfoService backupInfoService;

    public BackupJob(String tableName, String details, BackupInfoService backupInfoService) {
        this.tableName = tableName;
        this.details = details;
        this.backupInfoService = backupInfoService;
    }

    private String generateBackupFileName() {
        return tableName
                + "_"
                + new Date().getTime()
                + ".sql";
    }


    @Override
    protected Boolean runMethod() throws Exception {
        String backupFileName = generateBackupFileName();
        backupFilePath = new File(backupFolder, backupFileName)
                .getAbsolutePath();
        super.data("backupFileName", backupFileName);
        // 备份数据库信息
        if (ShellUtil.executeCommand(
                BACKUP_SHELL_PATH,
                DATABASE_NAME,
                tableName,
                backupFilePath)) {
            // 添加备份信息到数据库
            if (backupInfoService.save(new BackupInfo(
                    tableName,
                    details,
                    backupFileName))) {
                return true;
            }
        }
        return false;
    }
}
